package com.zhixinglu.spring.boot.generator.nickname.service;

import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * RandomGeneratorService
 * </p>
 *
 * @author weixin
 * @date 2023/3/27 11:49
 */
@Service
public class NicknameGeneratorService {

    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyz";
    private static final int CHARACTER_LENGTH = CHARACTERS.length();
    private static final int NUMBER_LENGTH = 3;
    private static final int THREAD_POOL_SIZE = 10;
    private Set<String> generatedNicknames = new HashSet<>();

    private ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

    public void generateUniqueNicknames(int count) {
        while (generatedNicknames.size() < count) {
            executorService.submit(() -> {
                String randomNickname = generateRandomNickname();
                synchronized(generatedNicknames) {
                    generatedNicknames.add(randomNickname);
                }
                // 调用处理方法
                process(randomNickname);
            });
        }
    }

    private String generateRandomNickname() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < NUMBER_LENGTH; i++) {
            sb.append(random.nextInt(10));
        }
        for (int i = 0; i < NUMBER_LENGTH; i++) {
            sb.append(CHARACTERS.charAt(random.nextInt(CHARACTER_LENGTH)));
        }
        return sb.toString();
    }

    private void process(String randomNickname) {
        // 实现处理逻辑
        System.out.println("Processing random nickname: " + randomNickname);
    }

}
